package com.level.restful.util;


import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.StringWriter;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;


/**
 * @author tqf
 *
 * xml javaBean 互相转换
 *
 *
 */
public class XmlToBeanUtil {
    /**
     * xml转javaBean
     * @param xml 需要转换的xml字符串
     * @param obj javaBean对象
     * @return
     */
    public static Object xmlToBean(String xml, Object obj) {
        JAXBContext jc;
        try {
//			String xml = "<Response><ResponseCode>0</ResponseCode><ResponseMsg></ResponseMsg><Items><Item><DeptID>202</DeptID><DeptName>内科</DeptName></Item><Item><DeptID>205</DeptID><DeptName>外科</DeptName></Item><Item><DeptID>207</DeptID><DeptName>传染科</DeptName></Item><Item><DeptID>211</DeptID><DeptName>肿瘤科</DeptName></Item><Item><DeptID>213</DeptID><DeptName>急诊科</DeptName></Item><Item><DeptID>214</DeptID><DeptName>中医科</DeptName></Item><Item><DeptID>215</DeptID><DeptName>康复科</DeptName></Item><Item><DeptID>216</DeptID><DeptName>耳鼻咽喉科</DeptName></Item><Item><DeptID>217</DeptID><DeptName>口腔科</DeptName></Item><Item><DeptID>219</DeptID><DeptName>儿科</DeptName></Item><Item><DeptID>220</DeptID><DeptName>眼科</DeptName></Item><Item><DeptID>221</DeptID><DeptName>妇科</DeptName></Item><Item><DeptID>222</DeptID><DeptName>发热门诊</DeptName></Item><Item><DeptID>223</DeptID><DeptName>肠道门诊</DeptName></Item><Item><DeptID>224</DeptID><DeptName>肝炎门诊</DeptName></Item><Item><DeptID>225</DeptID><DeptName>肺结核门诊</DeptName></Item><Item><DeptID>226</DeptID><DeptName>骨伤科门诊</DeptName></Item><Item><DeptID>228</DeptID><DeptName>五官科</DeptName></Item></Items></Response>";
            xml = xml.replace("\"", "");
            jc = JAXBContext.newInstance(new Class[] { obj.getClass() });
            Unmarshaller um = jc.createUnmarshaller();
            InputStream is = new ByteArrayInputStream(xml.getBytes("utf-8"));
            return um.unmarshal(is);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String javaBeanToXml(Class clazz,Object bean){
        StringWriter sw = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
            Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
            sw = new StringWriter();
            //该值默认为false,true则不会创建即头信息,即<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
            jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            jaxbMarshaller.marshal(bean, sw);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return sw.toString();
    }

    public static void main(String [] str){

    }
}
